<template>
	<view>

		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel"
			@AddModuleData_select='AddModuleData_select'>
			<template #workbench>

				<m-drag-button :style="{ opacity: BtnShow ? 1 : 0 }" :isDock="true" :existTabBar="true"
					class="m-drag-button-view" :initialBottom="60">
					<template #BtnContent>
						<u-icon name="search" color="#fff" size="25px" @click="search"></u-icon>
					</template>
				</m-drag-button>

			</template>

			<!-- 主内容 -->
			<template #content>
				<view class="content_box f-dc">
					<view class="table table_top_th">
						<table>
							<tr>
								<th width='8%'>计划日期</th>
								<th width='12%'>派工单编号</th>
								<th width='11%'>产品名称</th>
								<th width='6%'>计划数量</th>
								<th width='12%'>最新首检时间</th>
								<th width='6%'>上模状态</th>
								<th width='20%'>操作</th>



							</tr>
						</table>
					</view>

					<z-paging ref="paging" v-model="contents" @query="queryList" :fixed="false" class="z_paging">
						<view class="table" style="overflow-x: auto;width: 100%;">
							<table>
								<tbody>
									<tr v-for="(item,index) in contents" :class="rowClass(item.FStateName)">
										<td width='8%'>
											<view class="newlineDiv"><text>{{item.BillDate}}</text></view>
										</td>
										<td width='12%'>
											<view class="newlineDiv"><text>{{item.PGBillNo}}</text></view>
										</td>

										<td width='11%'>
											<view class="newlineDiv"><text>{{item.ProductName}}</text></view>
										</td>

										<td width='6%'>
											<view class="newlineDiv"><text>{{item.FPlanQty}}</text></view>
										</td>
										<td width='12%'>
											<view class="newlineDiv"><text>{{item.SJJDate}}</text></view>
										</td>

										<td width='6%'>
											<view class="newlineDiv"><text>{{item.SMStatus }}</text></view>
										</td>
										<td width='20%'>
											<view class="buttons">

												<u-button type="primary" text="上模" size='large' :style="{									
												backgroundColor: item.SMStatus === '上模中' ? '#CCCCCC' : '#3c9cff'
												}" :disabled="item.SMStatus =='上模中'" @click='firstdetailsClick(item,"上模")'></u-button>

												<u-button type="error" text="下模" size='large' :style="{
												backgroundColor: item.SMStatus ==''||item.SMStatus =='已下模' ? '#CCCCCC' : '#dbb56a'
												}" :disabled="item.SMStatus ==''||item.SMStatus =='已下模'" @click='firstdetailsClick(item,"下模")'></u-button>

												<u-button type="warning" text="首检" size='large'
													@click='firstdetailsClick(item,"首检")'></u-button>

												<u-button type="primary" text="试模" size='large' :style="{
													backgroundColor:item.IFSM ==0 ? '#CCCCCC' : '#D8BFD8'
													}" :disabled="item.IFSM ==0" @click='firstdetailsClick(item,"试模")'></u-button>
											</view>

										</td>
									</tr>
								</tbody>
							</table>

						</view>

					</z-paging>

				</view>


				<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
					<view class="popup_content">
						<u-cell-group :border='false'>



							<u-cell title="开始时间" :isLink="false" :value='FormData.FBDate'
								@click="addTime('开始时间')"></u-cell>
							<u-cell title="结束时间" :isLink="false" :value='FormData.FEDate'
								@click="addTime('结束时间')"></u-cell>

						</u-cell-group>
						<view class="bottomBtns">
							<button block @click="submit">
								查 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp 询
							</button>
						</view>

					</view>
				</uni-popup>
				<!-- 
				<view class="search">
					<u-icon name="search" color="#fff" size="30" @click="search"></u-icon>
				</view> -->
				<u-datetime-picker :show="Timeshow" v-model="Timevalue1" mode="date" @cancel='show = false'
					@confirm='pickerConfirm'></u-datetime-picker>

				<u-toast ref="uToast"></u-toast>

			</template>

		</st-mc-framework>
		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
		<u-popup :show="PopupShow" mode="center" @close="PopupClose" @open="PopupOpen" :round="10">
			<view class="Popup_view">
				<web-view :src="pdfUrl" class="custom-webview" :fullscreen='false'></web-view>

			</view>
		</u-popup>
	</view>
</template>

<script>
	const open = uni.requireNativePlugin("Html5App-openFile");
	import toast from '../../uni_modules/uview-ui/libs/config/props/toast';
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				pdfUrl: '',
				PopupShow: false,
				modalshow: false,
				modaltitle: '',
				modalcontent: '',
				ModuleTitle: '', //标题名称
				showMLoading: false, //是否加载
				loadingName: '正在加载中……', //加载名称
				disabled: false, //按钮是否点击
				FormData: {
					UserName: '',
					PageIndex: 1,
					PageSize: 30,
					FBDate: '',
					FEDate: '',
					EquipmentID: 0,
					EquipmentName: '',
					IsStart: 0,
					FState: 0,
					FWorkshopID: null,
				},
				contents: [], //列表
				Timeshow: false, //时间显示
				Timevalue1: Number(new Date()), //时间值
				TimeName: '', //时间名称
				BtnShow: false, //按钮显示
			};
		},

		onReady() {
			var that = this
			uni.hideLoading();
			that.showMLoading = true
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(options) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			if (options.Dispatchitem) {
				const dispatchItem = JSON.parse(options.Dispatchitem);
				that.assignFormData(that.FormData, dispatchItem);
				return;
			}
			const formDefaults = {
				FBDate: getBefore7DateTime(),
				FEDate: getFormatDateTime(new Date()),
				FWorkshopID: MesBasicInfo.FWorkshopID,
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
				UserName: UserInfo.UserName,
			};
			that.assignFormData(that.FormData, formDefaults);
		},
		onShow() {
			var that = this
			uni.$on('refreshList', () => {
				this.getList(); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshList');
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		mounted() {
			var that = this

		},
		computed: {
			// 计算属性返回一个函数
			rowClass() {
				return (status) => ({
					'active-row-yellow': status === '已开工',
					'inactive-row-green': status === '已完成'
				});
			}
		},
		methods: {
			PopupClose() {
				this.show = false
			},
			PopupOpen() {
				this.show = false
			},
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			firstdetailsClick(item, title) {
				var that = this
				console.log(item);
				var obj
				let routes = getCurrentPages();
				var url
				if (title == '试模') {

					if (item.SMStatus == '' || item.SMStatus == '已下模' && item.SJJDate) {
						that.showModal('提示', '请先上模并且要做 首检合格后');
					} else {
						let queryString = `Dispatchitem=${JSON.stringify(item)}`;
						url = `/st_mes_zs/common/Pdflist?${queryString}`
						obj = {
							path: 'manual',
							Name: '试模详情',
							APPFunID: '试模详情',
							path: 'manual',
							length: routes.length + 1,
							url: url,
						}
						uni.navigateTo({
							url: url
						})
					}


				} else if (title == '首检') {
					let queryString = `Dispatchitem=${JSON.stringify(item)}&name=生产派工`;
					url = `/st_mes_zs/test/firstinspectionDetail?${queryString}`
					obj = {
						path: 'manual',
						Name: '首件检详情',
						APPFunID: '首件检详情',
						path: 'manual',
						length: routes.length + 1,
						url: url,
					}
					this.GonavigateTo(obj, url)
				} else if (title == '上模') {
					url = `/st_mes_zs/poweron/upMoldDetail?Dispatchitem=${JSON.stringify(item)}&name=生产派工`
					obj = {
						path: 'manual',
						Name: '上模详情',
						APPFunID: '上模详情',
						length: routes.length + 1,
						url: url,
					}
					this.getZS_getSMoldID(obj, url, item, title)
				} else {
					url = `/st_mes_zs/poweron/downMoldDetail?Dispatchitem=${JSON.stringify(item)}&name=生产派工`
					obj = {
						path: 'manual',
						Name: '下模详情',
						APPFunID: '下模详情',
						length: routes.length + 1,
						url: url,
					}
					this.getZS_getSMoldID(obj, url, item, title)
				}
			},
			getZS_getSMoldID(obj, url, item, title) {
				var that = this
				that.Request.request('ZS_getSMoldIDByJobOrderID', {
					JobOrderID: item.JobOrderID,
					EquipmentID: that.FormData.EquipmentID
				}, function(res) {
					console.log(res);
					if (res.data.ds.length > 0 && res.data?.ds?.[0]?.cc % 2 != 0) {
						switch (title) {
							case '上模':
								that.showModal('提示', '当前设备已有下模模具，请先下模！');
								break;
							case '下模':
								that.GonavigateTo(obj, url)
								break;
						}
					} else if (res.data.ds.length > 0 && res.data?.ds?.[0]?.cc % 2 == 0) {
						switch (title) {
							case '上模':
								that.GonavigateTo(obj, url)
								break;
							case '下模':
								that.showModal('提示', '当前设备未有上模模具，请先上模！');
								break;
						}
					} else {
						that.GonavigateTo(obj, url)
					}

				})
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			getList() {
				this.contents = []; // 假设这是异步获取数据的操作
				this.$refs.paging.reload();
			},


			GonavigateTo(obj, url) {
				let that = this;
				var initData = JSON.parse(JSON.stringify(that.$store.state.GuyueModule.ModuleData_select));
				var parentData = initData[initData.length - 1]
				parentData.url = `/st_mes_zs/production/dispatchinglist?Dispatchitem=${JSON.stringify(that.FormData)}`;
				that.$modifyParentData(parentData);
				this.$safeNavigate({
					targetUrl: url, // 目标页面路径
					payload: obj, // 要传递的数据
				});
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			addTime(name) {
				this.TimeName = name
				if (this.TimeName == '开始时间') {
					this.Timevalue1 = Number(getTimeStamp(this.FormData.FBDate))
				} else {
					this.Timevalue1 = Number(getTimeStamp(this.FormData.FEDate))
				}
				this.Timeshow = true
			},
			search() {
				this.$refs.popup.open('bottom')
			},

			submit() {
				let that = this;
				this.$refs.popup.close('bottom')
				this.contents = []; // 假设这是异步获取数据的操作
				this.$refs.paging.reload();
			},
			pickerConfirm(e) {
				let that = this;
				var time = getFormatDateTime(e.value)
				if (this.TimeName == '开始时间') {
					this.FormData.FBDate = time
				} else {
					this.FormData.FEDate = time
				}
				this.Timeshow = false
			},
			queryList(pageNo) {
				let that = this;
				that.FormData.PageIndex = pageNo
				try {
					that.Request.request('getWOJobOrderListKGM_ZS', that.FormData, (ret) => {
						console.log(ret);
						if (ret.status == 200) {
							that.showMLoading = false
							ret.data.ds.map(item => {
								item.BillDate = formatDateTime(item.BillDate)
								item.SJJDate = formatDateTime(item.SJJDate)
							})
							that.$refs.paging.complete(ret.data.ds);
						} else {
							that.showMLoading = false
						}
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			changeLevel(list, data, row) {
				getchangeLevel(data)

			},


		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.Popup_view {
		width: 70vw;
		height: 70vh;

		.custom-webview {
			width: 100%;
			height: 100%;
		}
	}

	.active-row-yellow td text {
		color: #fcc105;
	}

	.inactive-row-green td text {
		color: green;
	}




	.buttons {
		display: flex;
		align-items: center;
		width: 100%;
		justify-content: space-between;
		height: 100%;

		.u-button {
			border: none;
			width: fit-content;
			margin: 1%;
			height: 40px;
			font-size: 22px;
		}
	}
</style>